/* 中间主编辑区域
* MiddleEditZone.jsx
*/
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { push } from 'redux-router';

import {getPageComponents,computePull,showMessage} from '../../utils/H5helper';
import {addNewLabel,addNewImage,addNewText,addNewTextarea,addNewSelect,upCompSurface} from '../../actions/h5/ComponentAction';
import {saveAllDatas,loadPreviewData} from '../../actions/h5/H5Action';
import {listImage} from '../../actions/FileHandleAction';


import UploadComponent from '../../components/UploadComponent.jsx';
import Preview from './Preview.jsx';

import {SUBMIT_BTN_IMG_SRC} from '../../utils/H5constants';
//主编辑区域上部的按钮组，主要是新增组件
class EditButtonGroup extends Component{
	constructor(props){
		super(props);
		this.state={
			previewSaving:false,
			saving:false
		}
	}

	componentDidMount(){
		//上传按钮
		$('.uploadBtn').popup({
    		popup : $('#uploadPopup'),
    		on   : 'click'
  		});
		//表单按钮
  		$('.formBtn').dropdown();
  		//加载提交按钮图片
  		let img = new Image();
		img.src = SUBMIT_BTN_IMG_SRC;

		//保存按钮,显示保存成功提示
		$("#saveBtn").popup({
			position:'bottom left',
			on : 'manual'
		});
	}

	componentWillUnmount(){
		$('.uploadBtn').popup('remove popup');
		$('#saveBtn').popup('remove popup');
	}

	//新增文本框
	addNewLabel(){
		this.props.dispatch(addNewLabel(this.props.pageId));
	}
	//上传按钮点击
	uploadBtnClick(){
		this.props.dispatch(listImage(null,null,10));//加载服务器的h5图片
	}

	//点击上传图片控件中的图片事件
	imgClick(src,imgName){
		this.props.dispatch(addNewImage(this.props.pageId,src,imgName));
	}

	//点击新增单行文本框
	formBtnClick(name){
		switch(name){
			case 'text':
				this.props.dispatch(addNewText(this.props.pageId));
				break;
			case 'textarea':
				this.props.dispatch(addNewTextarea(this.props.pageId));
				break;
			case 'select':
				this.props.dispatch(addNewSelect(this.props.pageId));
				break;
			case 'textBtn':
				this.props.dispatch(addNewLabel(this.props.pageId,'提交','#8fc31f'));
				break;
			case 'imageBtn':
				this.props.dispatch(addNewImage(this.props.pageId,SUBMIT_BTN_IMG_SRC,'submitBtn'));
				break;
		}
	}
	//显示预览页面
	showPreview(){
		/*this.setState({previewSaving:false});
		$('#viewPopup').modal('setting', 'closable', false).modal("show");
		const loadHtml='<div class="lg-container"><div class="lg-page-container"><ul class="islider-outer"><li>'+
							'<div class="ui segment view-page"><div class="ui active dimmer">'+
								'<div class="ui large  text loader">加载中</div>'+
							'</div></div>'+
						'</li></ul></div></div>';
		$('#previewPcHtml').html(loadHtml);
		$(".preview .right .title").html(this.props.h5title)
		//服务端加载渲染数据
		const uniqueCode=this.props.uniqueCode;
		loadPreviewData(uniqueCode).then(res=>{
			$('#preview_qrcode').attr('src','data:image/png;base64,'+res.qrcode);//设置二维码图片
			$('#previewPcHtml').html(res.html);
		});*/
		this.setState({previewSaving:false});
		const uniqueCode=this.props.uniqueCode;
		if(window){
			const pageNum=this.props.pageData.get("pageNum");
			window.open('../preview/uniqueCode/'+uniqueCode+"/pageNum/"+pageNum);
		}
		
	}
	//预览按钮
	previewBtnClick(){
		if(this.props.saveDatas.id){
			console.log('点击预览按钮，保存数据');
			this.setState({previewSaving:true});
			this.props.dispatch(saveAllDatas(this.props.saveDatas,this.showPreview.bind(this)));
		}
	}
	//保存按钮
	save(){
		console.log('保存数据');
		this.setState({saving:true});
		this.props.dispatch(saveAllDatas(this.props.saveDatas,()=>{
			//回调显示保存成功提示
			this.setState({saving:false});
			$("#saveBtn").popup('show');
			setTimeout(function(){
				$("#saveBtn").popup('hide');
			},600);
		}));
	}

	toPublicSetPage(){
		this.props.dispatch(push(__ROOTPATH__+'h5edit/publicSet/' + this.props.uniqueCode));
	}

	//点击发布按钮
	publicH5(){
		/*if(this.props.saveDatas.id){
			console.log('点击预览按钮，保存数据');
			this.setState({previewSaving:true});
			this.props.dispatch(saveAllDatas(this.props.saveDatas,this.showPreview.bind(this)));
		}*/
		this.props.dispatch(push(__ROOTPATH__+'h5edit/publicSet/' + this.props.uniqueCode));
	}

	render(){
		const upCompProps={//上传组件的属性
			width:530,
			height:350,
			showTabs:['image','file','music'],//显示的标签页
			imgClick:this.imgClick.bind(this),//设置图片点击事件
			multiple:true   //是否允许多个文件同时上传
		}
		let saveBtnClass="ui button";
		if(this.state.saving){
			saveBtnClass="ui loading button";
		}
		let previewBtnClass="ui button";
		if(this.state.previewSaving){
			previewBtnClass="ui loading button";
		}
		return (
			<div className="ui grid editButtonGroup">
		  		<div className="one wide column ">
			  		<div className="ui small basic icon buttons">
						<button id="saveBtn" className={saveBtnClass} onClick={this.save.bind(this)} data-content="保存成功"><i className="save icon"></i></button>
					</div>
				</div>
		  		<div className="eleven wide column">
				    <button className="ui blue mini button" onClick={()=>{this.addNewLabel()}}><i className="font icon"></i>文本</button>
				    <button className="ui blue mini button uploadBtn" onClick={this.uploadBtnClick.bind(this)}><i className="file Image Outline icon"></i>上传</button>
				    {/*<button className="ui blue mini button"><i className="plug icon"></i>插件</button>*/}
				    <button className="ui blue mini button dropdown formBtn">
				    	<i className="list icon"></i>表单
				    	<div className="menu">
						    <div className="item" onClick={()=>this.formBtnClick('text')}>单行文本框</div>
						    <div className="item" onClick={()=>this.formBtnClick('textarea')}>多行文本框</div>
						    <div className="item" onClick={()=>this.formBtnClick('select')}>下拉框</div>
						    <div className="item" onClick={()=>this.formBtnClick('textBtn')}>文本按钮</div>
						    <div className="item" onClick={()=>this.formBtnClick('imageBtn')}>图片按钮</div>
					    </div>
					</button>
				</div>
				<div className="three wide column">
					<div className="ui mini teal buttons right floated">
					  <button className={previewBtnClass} onClick={this.previewBtnClick.bind(this)}>预览</button>
					  <div className="or" style={{zIndex:0}}></div>
					  <button className="ui button" onClick={this.publicH5.bind(this)}>发布</button>
					</div>
				</div>
				<div id="uploadPopup" className="ui custom popup">
					<UploadComponent {...upCompProps} />
				</div>
				<div id="viewPopup" className="ui basic modal preview">
  					<Preview />
				</div>
			</div>
		)
	}
}


//中间主编辑区域
class MiddleEditZone extends Component{
	constructor(props){
		super(props);
		this.dragStartXY={};
		this.compDraging=false;//组件是否在拖动中
		this.selPull={pulling:false,name:''};//选中框拉伸
	}

	componentDidMount(){

	}

	componentWillUnmount(){
		$(".ui.dimmer.modals").find("#viewPopup").remove();//删除预览的弹出层的popup，这是由jquery渲染的，要手动删除
	}

	setSelectStyle(comp){//在组件的操作过程中，重新设定选中框的style
		this.props.setSelectComp(comp);
	}

	clearSelect(e){//清除选中框
		if(e){
			e.preventDefault()|| e.stopPropagation();
		} 
		this.props.hiddenSelComp();//调用父组件的方法让选中框隐藏
	}

	dragOver(e){//编辑区域拖放事件
		 e.preventDefault()|| e.stopPropagation();
	}

	moveCompPos(moveX,moveY){
		const surface=this.props.selComp.get('surface');
		const newX=parseInt(surface.get('x'))+moveX;
		const newY=parseInt(surface.get('y'))+moveY;
		this.props.dispatch(upCompSurface(this.pageId,this.props.selComp.get('id'),{x:newX,y:newY}));
		//选中框修改
		const newSurface=surface.merge(Immutable.Map({x:newX,y:newY}));
		const newSelComp=this.props.selComp.set('surface',newSurface);
		this.setSelectStyle(newSelComp);
	}

	//组件拖动结束后，外层的编辑区域会监听到drop事件，进行组件位置移动的处理
	drop(e){//编辑区域拖动释放
    	if(this.compDraging){//针对组件拖动
    		//计算鼠标移动位移
			const moveX=e.pageX - this.dragStartXY.x;
    		const moveY=e.pageY - this.dragStartXY.y;
			this.moveCompPos(moveX,moveY);
		}
		if(this.selPull.pulling){
			//计算鼠标移动位移
			const mx=e.pageX - this.dragStartXY.x;
			const my=e.pageY - this.dragStartXY.y;
			this.drawComp(mx,my,this.selPull.name);
		}
        e.preventDefault() || e.stopPropagation();  //不取消，firefox中会触发网页跳转到查找setData中的内容
	}

	compDragStart(e,id){//组件拖动开始，移动组件的位置，记录组件的初始鼠标点
		e.dataTransfer.effectAllowed = "move";  //移动效果
		e.dataTransfer.setData("text", '');  //附加数据，　没有这一项，firefox中无法移动
		this.dragStartXY.x=e.pageX;
		this.dragStartXY.y=e.pageY;
		this.compDraging=true;
		const comp=this.props.pageData.get('components').get(id);
		this.setSelectStyle(comp);
	}

	compDragEnd(e,id){//组件拖放结束，移动组件的位置。
		this.compDraging=false;
	}
	
	drawComp(mx,my,name){//选中框的点拖动过程中对组件和选中框的宽高xy坐标的重新设置
		//console.log(mx+'----'+my);
		if(mx!=0 || my!=0){
			const {moveX,moveY,widthAdd,heightAdd}=computePull(mx,my,name);
			const newWidth=this.selPull.width+widthAdd;
			const newHeight=this.selPull.height+heightAdd;
			const newX=this.selPull.x+moveX;
			const newY=this.selPull.y+moveY;

			if(newWidth<0||newHeight<0){
				return;
			}

			const newPos={x:newX,y:newY,width:newWidth,height:newHeight};
			//console.log(newPos);
			this.props.dispatch(upCompSurface(this.pageId,this.props.selComp.get('id'),newPos));
			//选中框修改
			const newSurface=this.props.selComp.get('surface').merge(newPos);
			const newSelComp=this.props.selComp.set('surface',newSurface);
			this.props.setSelectComp(newSelComp);
			//this.props.setSelectCompStyle(newX+'px',newY+'px',newWidth+'px',newHeight+'px');
		}
		
	}

	selectDragStart(e,name){//选中框拖动开始
		e.dataTransfer.effectAllowed = "move";  //移动效果
		e.dataTransfer.setData("text", '');  //附加数据，　没有这一项，firefox中无法移动
		this.dragStartXY.x=e.pageX;
		this.dragStartXY.y=e.pageY;

		this.selPull.pulling=true;
		this.selPull.name=name;
		const surface=this.props.selComp.get('surface');
		this.selPull.x=parseInt(surface.get('x'));
		this.selPull.y=parseInt(surface.get('y'));
		this.selPull.width=parseInt(surface.get('width'));
		this.selPull.height=parseInt(surface.get('height'));
	}

	selectDraging(e,name){//选中框拖动过程中
		//一边拖动一边渲染有性能问题
		/*if(this.selPull.pulling){
			//计算鼠标移动位移
			const mx=e.pageX - this.dragStartXY.x;
			const my=e.pageY - this.dragStartXY.y;
			this.drawComp(mx,my,name);
		}*/
		e.preventDefault() || e.stopPropagation();  //不取消，firefox中会触发网页跳转到查找setData中的内容
	}

	selectDragEnd(e){//选中框拖动结束
		this.selPull.pulling=false;
	}

	render(){
		this.pageId=this.props.pageData.get('id');
		//组件的事件
		const compHandleProps={
			dragStart:this.compDragStart.bind(this),
			dragEnd:this.compDragEnd.bind(this),
			onSelectComp:this.setSelectStyle.bind(this),//组件单击选中
			editStage:true
		};
		//获取页面初始化的组件
		const components=getPageComponents(this.props.pageData,compHandleProps);
		//上方按钮主属性
		const btnGroupProps={
			dispatch:this.props.dispatch,
			pageId:this.pageId,
			saveDatas:this.props.saveDatas,
			uniqueCode:this.props.uniqueCode,
			h5title:this.props.h5title,
			pageData:this.props.pageData
		}
		const attributes=this.props.pageData.get('attributes');
		let bgStyle={opacity:attributes.get('backgroundOpacity')};
		if(attributes.get('background')!=''){
			bgStyle={
					opacity:attributes.get('backgroundOpacity'),
					background:attributes.get('background'),
					backgroundSize:'cover!important'
				}
		}
		return(
		  	<div className="page-editor-wrapper" style={{right:'300px'}}>
		  		<div className="page-editor-btnDiv"><EditButtonGroup {...btnGroupProps} /></div>
		  		<div className="page-state-phone-out"></div>
		  		<div className="page-stage-wrapper">
			  		<div id="estage" className="editor-stage" 
			  		onDragOver={this.dragOver.bind(this)} onDrop={this.drop.bind(this)} 
			  		onClick={this.clearSelect.bind(this)} >
			  		<div className="backface" style={bgStyle}></div>
			  			{components}
			  			{/*选中框 */}
						<div className="component-handles">
							<div className="lg-component-handle"  style={this.props.selectStyle}>
								<div className="handle nw" draggable="true" onDragStart={e=>{this.selectDragStart(e,'nw')}} onDrag={e=>{this.selectDraging(e,'nw')}} onDragEnd={e=>{this.selectDragEnd(e)}} ></div>
								<div className="handle n" draggable="true" onDragStart={e=>{this.selectDragStart(e,'n')}} onDrag={e=>{this.selectDraging(e,'n')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle ne" draggable="true" onDragStart={e=>{this.selectDragStart(e,'ne')}} onDrag={e=>{this.selectDraging(e,'ne')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle e" draggable="true" onDragStart={e=>{this.selectDragStart(e,'e')}} onDrag={e=>{this.selectDraging(e,'e')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle se" draggable="true" onDragStart={e=>{this.selectDragStart(e,'se')}} onDrag={e=>{this.selectDraging(e,'se')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle s" draggable="true" onDragStart={e=>{this.selectDragStart(e,'s')}} onDrag={e=>{this.selectDraging(e,'s')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle sw" draggable="true" onDragStart={e=>{this.selectDragStart(e,'sw')}} onDrag={e=>{this.selectDraging(e,'sw')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
								<div className="handle w" draggable="true" onDragStart={e=>{this.selectDragStart(e,'w')}} onDrag={e=>{this.selectDraging(e,'w')}} onDragEnd={e=>{this.selectDragEnd(e)}}></div>
							</div>
						</div>
			  		</div>
			  	</div>
			  	{/*消息显示的地方*/}
				<div>
			  		<div id="errMsg" className="ui hidden green floating message">
					  <p></p>
					</div>
				</div>

		  	</div>
		);
	}
}

/*//测试数据
import {imagelist} from '../../testData/ImageListData';
const imglist=Immutable.fromJS(imagelist);*/
function mapStateToProps(state,ownProps){
	const pageDatas=state.app.h5Reducer.data.pages;
	const activePageId=state.app.h5Reducer.activePageId?state.app.h5Reducer.activePageId:ownProps.pageId;
	return {
		uniqueCode:state.app.h5Reducer.uniqueCode,
		h5title:state.app.h5Reducer.title,
		pageData:pageDatas.get(activePageId),
		saveDatas:state.app.h5Reducer
	};
}

export default connect(mapStateToProps)(MiddleEditZone);